package reflect;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
/**
 * 自动调用与Test4在同一个包中那些被@AutoRunClass标注的类中被@AutoRunMethod
 * 标注的方法.
 */
public class Test4 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        File dir = new File(Test4.class.getResource(".").toURI());
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for(File file : subs){
            String fileName = file.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            Class cl = Class.forName(Test4.class.getPackage().getName()+"."+className);
            if (cl.isAnnotationPresent(AutoRunClass.class)){
                Object obj = cl.newInstance();
                Method[] methods = cl.getDeclaredMethods();
                for(Method method : methods){
                    if (method.isAnnotationPresent(AutoRunMethod.class)){
                        System.out.println("被@AutoRunClass标注的类中被@AutoRunMethod标注的方法:"+method.getName()+"() ");
                        method.invoke(obj);
                    }
                }
            }
        }
    }
}
